const fs = require('fs');
const path = require('path');

const Server = require('./Server');
const Skeleton = require('./Skeleton');

const PLUGIN_NAME = 'SkeletonPlugin';

class SkeletonPlugin {
  constructor(options) {
    this.options = options; //{staticDir port origin}
    this.server = null;
    this.skeleton = null;
  }
  apply(compiler) {
    console.log('--- --- --- --- --- --- ---')
    console.log('--- SkeletonPlugin apply ---')
    console.log('--- --- --- --- --- --- ---')
    compiler.hooks.done.tap(PLUGIN_NAME, async () => {
      console.log('--- --- --- --- --- --- ---')
      console.log('--- SkeletonPlugin done ---')
      console.log('--- --- --- --- --- --- ---')

      await this.startServer(); //启动一个http服务器

      this.skeleton = new Skeleton(this.options);
      await this.skeleton.initialize(); //通过puppeteer启动一个无头浏览器
      //生成骨架屏的html和style
      const skeletonHTML = await this.skeleton.genHTML(this.options.origin);
      console.log('skeletonHTML:',skeletonHTML);
      const originPath = path.resolve(this.options.staticDir, 'index.html');
      const originHtml = await fs.readFileSync(originPath, 'utf8');
      const finalHTML = originHtml.replace('<!-- shell -->', skeletonHTML);
      console.log('finalHTML:',finalHTML);
      await fs.writeFileSync(originPath, finalHTML);

      await this.skeleton.destroy();
      await this.server.close(); //完事后要关闭服务器
    });
  }

  async startServer(){
    this.server = new Server(this.options); //创建服务
    await this.server.listen(); //启动这个服务器
  }
}

module.exports = SkeletonPlugin;
